package com.sanda.androidcourse.chapter07;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import androidx.annotation.Nullable;
import android.widget.Toast;

public class MyServiceUseBind extends Service {
    private final IBinder binder = new LocalBinder();
    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 在此执行长时间运行的任务，例如：后台任务
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        return START_STICKY;  // 如果服务被杀死，系统会重新创建
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    }

    public class LocalBinder extends Binder {
        MyServiceUseBind getService() {
            return MyServiceUseBind.this;
        }
    }
}
